package com.lzb.musicplayer.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import com.lzb.musicplayer.R;


/**
 * 自定义圆角图片控件
 */
public class RoundImageView extends AppCompatImageView {
    
    private float[] radii = new float[8]; // 存储四个角的半径
    private Path path = new Path();
    private RectF rect = new RectF();
    
    public RoundImageView(Context context) {
        super(context);
        init(null);
    }
    
    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }
    
    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }
    
    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.RoundImageView);
            float radius = ta.getDimension(R.styleable.RoundImageView_radius, 8 * getResources().getDisplayMetrics().density);
            float topLeftRadius = ta.getDimension(R.styleable.RoundImageView_topLeftRadius, radius);
            float topRightRadius = ta.getDimension(R.styleable.RoundImageView_topRightRadius, radius);
            float bottomLeftRadius = ta.getDimension(R.styleable.RoundImageView_bottomLeftRadius, radius);
            float bottomRightRadius = ta.getDimension(R.styleable.RoundImageView_bottomRightRadius, radius);
            
            setRadius(topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius);
            ta.recycle();
        } else {
            // 默认圆角半径为8dp
            float radius = 8 * getResources().getDisplayMetrics().density;
            setRadius(radius);
        }
    }
    
    /**
     * 设置统一的圆角半径
     */
    public void setRadius(float radius) {
        for (int i = 0; i < 8; i++) {
            radii[i] = radius;
        }
        invalidate();
    }
    
    /**
     * 分别设置四个角的圆角半径
     */
    public void setRadius(float topLeft, float topRight, float bottomRight, float bottomLeft) {
        radii[0] = radii[1] = topLeft;
        radii[2] = radii[3] = topRight;
        radii[4] = radii[5] = bottomRight;
        radii[6] = radii[7] = bottomLeft;
        invalidate();
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        rect.set(0, 0, getWidth(), getHeight());
        path.reset();
        path.addRoundRect(rect, radii, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }
}